import styles from './Calendar.table.module.scss';
import moment from 'moment';
import 'moment/locale/ru';
import React, { useState } from 'react';
import arrow from '@shared/assets/svg/circle_arrow.svg';

const CalendarTable = () => {
	const [startDate, setStartDate] = useState(moment());

	window.moment = moment;
	moment.updateLocale('ru', { week: { dow: 1 } });
	const daysOfWeek = ['пн', 'вт', 'ср', 'чт', 'пт', 'сб', 'вс'];

	const nextTwoWeeks = () => {
		const newStartDate = startDate.clone().add(14, 'days');
		setStartDate(newStartDate);
	};

	const prevTwoWeeks = () => {
		const newStartDate = startDate.clone().subtract(14, 'days');
		setStartDate(newStartDate);
	};

	const renderCalendarDays = () => {
		return [...Array(14)].map((_, index) => {
			const currentDate = startDate.clone().add(index, 'days');
			return (
				<li key={index} className={styles['days_item']}>
					{currentDate.format('D')}
				</li>
			);
		});
	};

	const generateHeader = (startDate) => {
		const endDate = startDate.clone().add(13, 'days');

		const startMonth = startDate.format('MMMM YYYY');
		const capitalizedStartMonth =
			startMonth.charAt(0).toUpperCase() + startMonth.slice(1);

		const endMonth = endDate.format('MMMM YYYY');
		const capitalizedEndMonth =
			endMonth.charAt(0).toUpperCase() + endMonth.slice(1);

		if (startDate.month() === endDate.month()) {
			return capitalizedStartMonth;
		} else {
			return `${capitalizedStartMonth} - ${capitalizedEndMonth}`;
		}
	};

	return (
		<div className={styles.datepicker}>
			<header className={styles.top}>
				<button onClick={prevTwoWeeks} className={styles.btn}>
					<img className={styles.arrow} src={arrow} />
				</button>
				<h3 className={styles['month_title']}>{generateHeader(startDate)}</h3>
				<button onClick={nextTwoWeeks} className={styles.btn}>
					<img className={styles.arrow} src={arrow} />
				</button>
			</header>
			<div className={`${styles['grid_wrap']}`}>
				<ul className={`${styles.grid} ${styles.weeks}`}>
					{daysOfWeek.map((item) => (
						<li key={item} className={styles['weeks_item']}>
							{item}
						</li>
					))}
				</ul>
				<ul className={`${styles.grid} ${styles.days}`}>
					{renderCalendarDays()}
				</ul>
			</div>
		</div>
	);
};

export default CalendarTable;
